package org.beynet.docs.helpers;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

public class XmlHelper {
    
    
    /**
     * return a document builder
     * @return
     */
    public static DocumentBuilder getDocumentBuilder() {
        return(documentBuilders.get());
    }
    
    /**
     * return an xpath interpretor for atom used in gdocs feeds
     * @return
     */
    public static XPath getXPathInterpretorForGDocsAtom() {
        return(xpathsForGDocsAtom.get());
    }

    private static final ThreadLocal<DocumentBuilder> documentBuilders = new ThreadLocal<DocumentBuilder>() {
        @Override
        protected DocumentBuilder initialValue() {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                return(dbf.newDocumentBuilder());
            } catch (Exception e) {
                throw new RuntimeException("unable to create a new document builder for this thread",e);
            }
        }
    };
    
    private static final ThreadLocal<XPath> xpathsForGDocsAtom = new ThreadLocal<XPath>() {
        @Override
        protected XPath initialValue() {
            XPath xpath = XPathFactory.newInstance().newXPath();
            xpath.setNamespaceContext(new GDocsAtomNameSpaceContext());
            return(xpath);
        }
        
    };
    
}
